import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;

public class CreateFile extends Form implements CommandListener{
	private FileManagerMIDlet filemanager;
	private ListContend list;
	private String url,createurl;
	private TextField name;
	private ChoiceGroup choice;
	private Command ok, cancel;
	private FileConnection fileconn;
	private Connector conn;
	public CreateFile(FileManagerMIDlet fm, ListContend list, String currenturl){
		super("Tao moi");
		this.filemanager = fm;
		this.url = currenturl;
		this.list = list;
		name = new TextField("Nhap ten", "", 255, TextField.ANY);
		choice = new ChoiceGroup("Ban muon tao",Choice.POPUP);
		choice.append("Thuc muc",null);
		choice.append("Tap tin",null);
		ok = new Command("Tao", Command.OK, 0);
		cancel = new Command("Huy", Command.CANCEL, 1);
		append(name);
		append(choice);
		addCommand(ok);
		addCommand(cancel);
		setCommandListener(this);
	}
	public boolean checkExist(String newfileurl){
		try{
			fileconn = (FileConnection) conn.open(newfileurl);	
			if(fileconn.exists() == true){
				filemanager.showAlert("Trung ten voi tap tin hoac thu muc !", this);
				return true;					
			}
			else
				return false;
		}
		catch(Exception e){
			filemanager.showAlert("Ten khong duoc chua cac ky tu dac biet, ten khong duoc bat dau  bang dau cham hoac khoang trang !", this);
			return true;
		}				
	}
	public void createFile(String fileurl, boolean filetype){
		if(filetype == true)
			try{
				fileconn = (FileConnection) conn.open(fileurl);
				fileconn.mkdir();
				list.getContend(url, null);
				filemanager.showAlert("Da tao thu muc: " + name.getString(), list);
			}
			catch(Exception e){
				filemanager.showAlert("Ten khong duoc chua cac ky tu dac biet, ten khong duoc bat dau  bang dau cham hoac khoang trang !", this);				
			}
		else if(filetype == false){
			try{
				fileconn = (FileConnection) conn.open(fileurl);
				fileconn.create();
				list.getContend(url, null);
				filemanager.showAlert("Da tao tap tin: " + name.getString(), list);
			}
			catch(Exception e){
				filemanager.showAlert("Ten khong duoc chua cac ky tu dac biet, ten khong duoc bat dau  bang dau cham hoac khoang trang !", this);
			}
		}		
	}
	public void commandAction(Command c, Displayable d){
		if(c == ok){
			if(choice.getSelectedIndex() == 0){			
				if(checkExist(url + name.getString()) == false)
					createFile(url + name.getString() + "/",true);	
			}
			else{				
				if(checkExist(url + name.getString()) == false)
					createFile(url + name.getString(), false);
			}
		}
		if(c == cancel){
			filemanager.showContend(url, null);
		}
	}
}